package cn.wolfcode.luowowo.website.controller;


import cn.wolfcode.luowowo.article.domain.Destination;
import cn.wolfcode.luowowo.article.domain.StrategyDetail;
import cn.wolfcode.luowowo.article.domain.Travel;
import cn.wolfcode.luowowo.article.domain.TravelContent;
import cn.wolfcode.luowowo.article.query.TravelQuery;
import cn.wolfcode.luowowo.article.service.IDestinationService;
import cn.wolfcode.luowowo.article.service.IStrategyDetailService;
import cn.wolfcode.luowowo.article.service.ITravelService;
import cn.wolfcode.luowowo.cache.service.ITravelStatisRedisService;
import cn.wolfcode.luowowo.cache.util.RedisKeys;
import cn.wolfcode.luowowo.cache.vo.TravelStatisVO;
import cn.wolfcode.luowowo.comment.domain.TravelComment;
import cn.wolfcode.luowowo.comment.query.StrategyCommentQuery;
import cn.wolfcode.luowowo.comment.service.ITravelCommentService;
import cn.wolfcode.luowowo.common.util.AjaxResult;
import cn.wolfcode.luowowo.common.util.LogicException;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.annotation.RequireLogin;
import cn.wolfcode.luowowo.website.annotation.UserParam;
import cn.wolfcode.luowowo.website.util.UMEditorUploader;
import cn.wolfcode.luowowo.website.util.UploadUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author 猫教授
 * @date 2019/8/11 23:31
 */
@Controller
@RequestMapping("travel")
public class TravelController {

    @Reference
    private ITravelService travelService;
    @Reference
    private IDestinationService destinationService;
    @Reference
    private IStrategyDetailService strategyDetailService;
    @Reference
    private ITravelCommentService travelCommentService;
    @Reference
    private ITravelStatisRedisService travelStatisRedisService;
    @Value("${file.path}")
    private String filePath;

    @RequestMapping("/commentAdd")
    //@RequireLogin
    public String commentAdd(@UserParam UserInfo userInfo, TravelComment comment, Model model) {
        if (userInfo != null) {
            //首先我们保存评论,需要补全信息
            comment.setUserId(userInfo.getId());
            comment.setUsername(userInfo.getNickname());
            comment.setCity(userInfo.getCity());
            comment.setLevel(userInfo.getLevel());
            comment.setHeadUrl(userInfo.getHeadImgUrl());
            comment.setCreateTime(new Date());
            //保存评论
            TravelComment travelComment = travelCommentService.save(comment);
            model.addAttribute("c", travelComment);
            //缓存也需要加一
            try {
                travelStatisRedisService.addStaticNum(comment.getTravelId(),1,TravelStatisVO.TRAVEL_STATISVO_REPLYNUM);
            } catch (Exception e){
                throw  new RuntimeException("评论失败");
            }


//        //返回内容
//        //增加文章评论内容,并且返回增加后的数量
//        int count=travelService.addReplynumByTravelId(comment.getTravelId());
//        //Long count=strategyCommentService.selectCountByTravelId(comment.getTravelId());
            model.addAttribute("floor", travelComment.getFloor());
            return "travel/commentTpl";
            //return JSON.toJSONString(new AjaxResult(true, "必须登录后才能进行操作喔"));
        } else {
            return "forward:/travel/jsoncomment";
        }

    }


    @RequestMapping("/jsoncomment")
    @ResponseBody
    public AjaxResult comment(Model model,@ModelAttribute("qo") StrategyCommentQuery qo) {

        return new AjaxResult(false,"需要登录");
    }


    @RequestMapping("")
    public String travel(Model model, @ModelAttribute("qo") TravelQuery qo) {
        model.addAttribute("pageInfo", travelService.selectForList(qo));
        model.addAttribute("tcs", travelCommentService.selectForTop10());

        return "travel/list";
    }

    @RequestMapping("getContent")
    @ResponseBody
    public TravelContent travel(Long travelId) {
        return travelService.getContent(travelId);
    }

    @RequireLogin
    @RequestMapping("input")
    public String input(Model model, Long id, @UserParam UserInfo userInfo) {

        if (id != null) {
            Travel travel = travelService.selectTravelById(id);
            //先判断要修改是不是自己的
            if (userInfo.getId() != travel.getAuthor().getId()) {
                throw new LogicException("这不是您的文章,您无权修改");
            }
            TravelContent content = travelService.getContent(id);
            travel.setTravelContent(content);
            model.addAttribute("tv", travel);
        }
        model.addAttribute("dests", destinationService.selectAll());
        return "travel/input";
    }

    @RequireLogin
    @RequestMapping("saveOrUpdate")
    @ResponseBody
    public AjaxResult saveOrUpdate(Travel travel, @UserParam UserInfo userInfo) {
        //进行保存工作
        Travel newTravel = travelService.saveOrUpdate(travel, userInfo);
        AjaxResult result = new AjaxResult();
        result.setSuccess(true);
        result.setData(newTravel.getId());
        return result;
    }

    @RequireLogin
    @RequestMapping("coverImageUpload")
    @ResponseBody
    public String coverImageUpload(MultipartFile pic) {
        String fileName = UploadUtil.upload(pic, filePath);
        return fileName;
    }

    //上传图片
    @RequireLogin
    @RequestMapping("/contentImage")
    @ResponseBody
    public String uploadUEImage(MultipartFile upfile, HttpServletRequest request) throws Exception {
        UMEditorUploader up = new UMEditorUploader(request);
        String[] fileType = {".gif", ".png", ".jpg", ".jpeg", ".bmp"};
        up.setAllowFiles(fileType);
        up.setMaxSize(10000); //单位KB
        up.upload(upfile, filePath);

        String callback = request.getParameter("callback");
        String result = "{\"name\":\"" + up.getFileName() + "\", \"originalName\": \"" + up.getOriginalName() + "\", \"size\": " + up.getSize()
                + ", \"state\": \"" + up.getState() + "\", \"type\": \"" + up.getType() + "\", \"url\": \"" + up.getUrl() + "\"}";
        result = result.replaceAll("\\\\", "\\\\");
        if (callback == null) {
            return result;
        } else {
            return "<script>" + callback + "(" + result + ")</script>";
        }
    }


    @RequestMapping("detail")
    public String detail(Long id, Model model) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        Travel travel = travelService.selectTravelById(id);
        TravelContent content = travelService.getContent(id);
        travel.setTravelContent(content);
        ArrayList<Destination> toasts = new ArrayList<>();
        Long destId = travel.getDest().getId();
        getToasts(destId, toasts);
        toasts.remove(0);
        model.addAttribute("toasts", toasts);
        //显示阅读量最大的文章
        List<StrategyDetail> strategyDetails = strategyDetailService.selectDetailsByDestIdNumTop3(destId);
        model.addAttribute("sds", strategyDetails);
        //查询点击量最大的三篇游记
        List<Travel> travels = travelService.selectTravelsByDestIdNumTop3(destId);
        model.addAttribute("ts", travels);
        //查询评论
        List<TravelComment> list = travelCommentService.selectCommentForList(id);
        model.addAttribute("list", list);
        //计算阅读数
        TravelStatisVO travelStatisVO = travelStatisRedisService.addStaticNum(id, 1, TravelStatisVO.TRAVEL_STATISVO_VIEWNUM);
        travel.setViewnum(travelStatisVO.getViewnum());
        model.addAttribute("detail", travel);
        return "travel/detail";
    }

    /**
     * 内部方法用来迭代吐丝的
     *
     * @param destinationId
     * @param toasts
     */
    private void getToasts(Long destinationId, ArrayList toasts) {
        Destination destination = destinationService.selecOne(destinationId);
        toasts.add(destination);
        if (destination.getParent() != null) {
            getToasts(destination.getParent().getId(), toasts);
        }
    }
    /**
     * 游记点赞或者顶操作
     * @param tid
     * @param userInfo
     * @return
     */
    @RequestMapping("/travelThumbup")
    @ResponseBody
    public AjaxResult travelThumbup(Long tid,@UserParam UserInfo userInfo) {
        //首先我们调用顶的方法
        //先进行登录判断
        if(userInfo==null){
            return new AjaxResult(false,"请先进行登录喔",null,102);
        }
        //如果有登录那么调用方法
        try {
            boolean result=travelStatisRedisService.isTravelThumbup(tid,userInfo.getId());
            if (result){
                travelStatisRedisService.addSortNum(RedisKeys.TRAVEL_STATIC_VO.getPrefix(),tid,1);
            }
            TravelStatisVO vo=travelStatisRedisService.getVoByTravelId(tid);
            return new AjaxResult(result,"",vo);
        }  catch (Exception e) {
            throw new RuntimeException("收藏失败");
        }
    }
    /**
     * 收餐内容
     * @param tid 游记的ID
     * @return
     */
    @RequestMapping("/favor")
    @ResponseBody
    public AjaxResult favor(Long tid,@UserParam UserInfo userInfo) {
        //首先我们调用顶的方法
        //先进行登录判断
        if(userInfo==null){
            return new AjaxResult(false,"请先进行登录喔",null,102);
        }
        //首先我们调用收藏的方法,收藏的方法
        try {
            boolean result=travelStatisRedisService.FavorByTravelId(tid,userInfo);
            if (result){
                travelStatisRedisService.addSortNum(RedisKeys.TRAVEL_COMMEND_SORT.getPrefix(),tid,1);
            }else {
                travelStatisRedisService.addSortNum(RedisKeys.TRAVEL_COMMEND_SORT.getPrefix(),tid,-1);
            }
            TravelStatisVO vo=travelStatisRedisService.getVoByTravelId(tid);
            return new AjaxResult(result,"",vo);
        } catch (Exception e) {
            throw new RuntimeException("收藏失败");
        }
    }



}
